<template>
  <div class="updataAddress">
    <topNav :title="'编辑'" :update="'保存'" @save="save" />
    <addressDetail />
  </div>
</template>

<script setup>
import addressDetail from "./components/addressDetail.vue";
import topNav from "./components/topNav.vue";
import { useRoute, useRouter } from "vue-router";
import { ref, watch, onUnmounted } from "vue";
import { post, put } from "../../utils/request.js";
import { Toast } from "vant";
import { setSession, getSession } from "../../utils/index.js";
import { mapMutations, mapState, mapActions, useStore } from "vuex";

const store = useStore();
const route = useRoute();
const router = useRouter();

const save = async () => {
  Toast.loading({
    message: "正在提交新地址，请稍后...",
    forbidClick: true,
    duration: 0,
  });
  let result;
  let data = getSession("address");
  console.log(data);
  let timer = null;
   if (data.default_set ) {
     updateDefault(data.id)
   }
  try {
    result = await put(`/address/${data.id}`, data);
  } catch (error) {
    console.log(error);
    timer = setTimeout(() => {
      Toast.clear();
      Toast.fail({ message: "提交失败，请稍后再试", forbidClick: true });
      clearTimeout(timer);
    }, 3000);
  }
  if (result.status == 200) {
    console.log(111111);
    Toast.clear();
    Toast.success({ message: "提交成功，跳回原页面", forbidClick: true });

    router.push("/myAddress");
  }
};
// 设置默认地址
const updateDefault = async (id) => {

    let result
  try {
    result = await post(`/setDefault/${id}`);
  } catch (error) {}
  if (result.status == 200) {
    console.log(result);
  }
};
onUnmounted(() => {
  Toast.clear();
  store.commit("address/setransformData", 2);
});
</script>

<style lang="scss" scoped>
.updataAddress {
  width: 100%;
  height: 100vh;
  background-color: #f1f1f1;
}
</style>
